package com.hezhiqin.formework.webmvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: homeWork
 * @description:
 * @author: hezhiqin
 * @create: 2019-11-01 11:51
 */
public class HZQView {

    private  final String DEFULAT_CONTENT_TYPE = "text/html;charset=utf-8";

    private File viewFile;

    public HZQView(File viewFile) {
        this.viewFile = viewFile;
    }

    //
    public  void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception{

        StringBuffer stringBuffer = new StringBuffer();

        //占位符替换成我们想要的字符
        RandomAccessFile raf = new RandomAccessFile(viewFile,"r");
        String line = null;
        //将占位符替换成对应的值
        while (null!=(line = raf.readLine())){
            line = new String(line.getBytes("ISO-8859-1"),"UTF-8");
            Pattern pattern = Pattern.compile("￥\\{[^\\}]+\\}",Pattern.CASE_INSENSITIVE);

            Matcher matcher = pattern.matcher(line);
            while (matcher.find()){
                String paramName = matcher.group();
                paramName = paramName.replaceAll("￥\\{|\\}","");
                Object oparamValue = model.get(paramName);
                if (null==oparamValue){
                    continue;
                }
                line = matcher.replaceFirst(makeStringForRegExp(oparamValue.toString()));

                matcher = pattern.matcher(line);
            }
            stringBuffer.append(line);
        }

        response.setCharacterEncoding("utf-8");
        response.getWriter().write(stringBuffer.toString());

    }

    //处理特殊字符
    public static String makeStringForRegExp(String str) {
        return str.replace("\\", "\\\\").replace("*", "\\*")
                .replace("+", "\\+").replace("|", "\\|")
                .replace("{", "\\{").replace("}", "\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }

}
